package com.lifeng.mynetty.server.tcp;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by lifeng
 * 2017/9/1 14:32
 */
public class TcpServer {
    private static Logger logger = LoggerFactory.getLogger(TcpServer.class);
    //监听端口
    private int port = -1;
    //字符编码
    private String charset = "UTF-8";
    /** 主线程最大数 */
    private int bossCount = 1;
    /** 工作线程最大数 */
    private int workerCount = 100;
    /**
     * 启动服务
     */
    public void start() throws Exception {
        logger.debug("端口:"+port);
        if(-1 == port){
            logger.error("端口:"+port+"配置有误");
            throw new Exception("端口:"+port+"配置有误");
        }
        //主线程数
        EventLoopGroup bossGroup = new NioEventLoopGroup(bossCount);
        //工作线程数
        EventLoopGroup workerGroup = new NioEventLoopGroup(workerCount);
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.childHandler(new TcpServerInitializer(charset));
            // 服务器绑定端口监听
            ChannelFuture future = serverBootstrap.bind(port).sync();
            logger.info("TCP服务已启动");
            // 监听服务器关闭监听
            future.channel().closeFuture().sync();

        }catch (Exception e){
            logger.error("初始化服务异常",e);
            throw new Exception("初始化服务异常",e);
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public int getBossCount() {
        return bossCount;
    }

    public void setBossCount(int bossCount) {
        this.bossCount = bossCount;
    }

    public int getWorkerCount() {
        return workerCount;
    }

    public void setWorkerCount(int workerCount) {
        this.workerCount = workerCount;
    }
}
